package hu.issue.ejb;

import hu.issue.entity.User;
import hu.issue.exceptions.UserAlreadyRegisteredException;
import hu.issue.exceptions.UserNotFoundException;
import hu.issue.framework.web.Constants;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class UserServiceBean implements UserService {
	@PersistenceContext
	private EntityManager manager;

	@EJB
	private RoleService roleService;

	@Override
	public void register(final User user, final String role) throws UserAlreadyRegisteredException {
		if (this.manager.find(User.class, user.getUserName()) != null) {
			throw new UserAlreadyRegisteredException();
		}

		if (role.equals(Constants.ROLE_PROJECTOWNER)) {
			user.getRoles().add(this.roleService.findByName(Constants.ROLE_USER));
		}
		user.getRoles().add(this.roleService.findByName(role));

		this.manager.persist(user);
	}

	@Override
	public User findUserByUserNameAndPassword(final String userName, final String password) {
		final Query query = this.manager.createQuery("select u from User u where u.userName = :username and u.password = :password");
		query.setParameter("username", userName);
		query.setParameter("password", password);
		try {
			return (User) query.getSingleResult();
		} catch (final NoResultException ex) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsers() {
		final Query query = this.manager.createQuery("select u from User u");
		return query.getResultList();
	}

	@Override
	public User findUserByUserName(final String userName) throws UserNotFoundException {
		final User user = this.manager.find(User.class, userName);
		if (user == null) {
			throw new UserNotFoundException();
		}
		return user;
	}
}
